import { WebformBuilder } from './webform-builder';
import { FarrisDesignBaseElement } from '../base-component/element';
import { BuilderOptions } from '../entity/builder-options';
import { ComponentSchema } from '../entity/builder-schema';

export default class Form extends FarrisDesignBaseElement {

    /** webFormBuilder类实例，用于外部监听表单的渲染后事件、变更事件等 */
    public instance: WebformBuilder;

    private innerForm: any = null;

    ready: Promise<any>;
    readyResolve: any;
    readyReject: any;

    get form(): any {
        return this.innerForm;
    }

    set form(value: any) {
        this.setForm(value);
    }

    constructor(public element: HTMLElement, builderSchema: ComponentSchema, options: BuilderOptions) {
        super(options);
        this.ready = new Promise((resolve, reject) => {
            this.readyResolve = resolve;
            this.readyReject = reject;
        });

        if (element instanceof HTMLElement) {
            this.element = element;
            this.options = options || {};
            // this.options.events = this.events;
            this.setForm(builderSchema).then(() => this.readyResolve(this.instance))
                .catch(this.readyReject);
        }
    }

    /**
     * 由外部触发更新子级组件列表，用于新增ComponentRef的场景
     * @param builderSchema 表单完整的DOM JSON
     * @param childComponents 子Component
     */
    updateChildComponents(builderSchema: ComponentSchema, childComponents: ComponentSchema[]) {
        // 更新根组件schema
        if (builderSchema) {
            // this.instance.webform.component = builderSchema;
            this.instance.webform._form = builderSchema;
        }
        // 更新子级组件
        if (childComponents) {
            this.options.childComponents = childComponents || [];
            this.instance.webform.options.childComponents = childComponents || [];
        }
    }

    setForm(formSchema: any): any {

        // 实际会调用子类DesignerBuilder的create方法，创建WebFormBuilder实例
        this.instance = this.instance || new WebformBuilder(this.element, this.options);

        // 为WebFormBuilder.form赋值会触发WebFormBuilder.setForm方法
        this.instance.form = this.innerForm = formSchema;

        const result = this.instance.ready;


        // a redraw has occurred so save off the new element in case of a setDisplay causing a rebuild.
        return result.then(() => {
            this.element = this.instance.element;
            return this.instance;
        });
    }

    destroy(): void {
        super.destroy();
    }


}